package com.apikey.auth.service.impl;

import com.apikey.auth.entity.ApiKey;
import com.apikey.auth.repository.ApiKeyRepository;
import com.apikey.auth.service.ApiKeyService;
import com.apikey.auth.service.HistoryService;
import com.apikey.auth.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.Predicate;
import java.security.SecureRandom;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * API Key管理服务实现类
 * 提供API Key的核心业务逻辑实现
 *
 * @author API Key Framework
 * @version 1.0
 */
@Service
@Transactional
public class ApiKeyServiceImpl implements ApiKeyService {

    @Autowired
    private ApiKeyRepository apiKeyRepository;

    @Autowired
    private HistoryService historyService;

    @Autowired
    private UserService userService;

    private static final String API_KEY_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    private static final int API_KEY_LENGTH = 32;
    private static final SecureRandom RANDOM = new SecureRandom();

    /**
     * 创建新的API Key
     */
    @Override
    public ApiKey createApiKey(String name, String permissions, String userId, String operatorId,
                               String description, Integer dailyLimit, Integer monthlyLimit, LocalDateTime expiresAt) {
        // 检查名称是否已存在
        if (existsByName(name)) {
            throw new IllegalArgumentException("API Key名称已存在: " + name);
        }

        // 生成唯一的API Key值
        String keyValue;
        do {
            keyValue = generateApiKeyValue();
        } while (existsByKeyValue(keyValue));

        // 创建API Key实体
        ApiKey apiKey = new ApiKey();
        apiKey.setName(name);
        apiKey.setKeyValue(keyValue);
        apiKey.setPermissions(permissions);
        apiKey.setStatus("ACTIVE");
        apiKey.setUserId(userId);
        apiKey.setDescription(description);
        apiKey.setDailyLimit(dailyLimit);
        apiKey.setMonthlyLimit(monthlyLimit);
        apiKey.setExpiresAt(expiresAt);

        // 保存API Key
        ApiKey savedApiKey = apiKeyRepository.save(apiKey);

        // 记录历史
        historyService.recordChange(savedApiKey, "CREATE", operatorId, "创建API Key");

        return savedApiKey;
    }

    /**
     * 根据ID查找API Key
     */
    @Override
    @Transactional(readOnly = true)
    public Optional<ApiKey> findById(Long id) {
        return apiKeyRepository.findById(id)
                .filter(apiKey -> !apiKey.getIsDeleted());
    }

    /**
     * 根据API Key值查找API Key
     */
    @Override
    @Transactional(readOnly = true)
    public Optional<ApiKey> findByKeyValue(String keyValue) {
        return apiKeyRepository.findByKeyValueAndIsDeletedFalse(keyValue);
    }

    /**
     * 分页查询所有API Key
     *
     * @param pageable 分页参数
     * @return API Key分页结果
     */
    @Override
    @Transactional(readOnly = true)
    public Page<ApiKey> findAll(Pageable pageable) {
        return apiKeyRepository.findByIsDeletedFalse(pageable);
    }

    /**
     * 根据用户ID分页查询API Key
     */
    @Override
    @Transactional(readOnly = true)
    public Page<ApiKey> findByUserId(String userId, Pageable pageable) {
        return apiKeyRepository.findByUserIdAndIsDeletedFalse(userId, pageable);
    }

    /**
     * 根据状态分页查询API Key
     */
    @Override
    @Transactional(readOnly = true)
    public Page<ApiKey> findByStatus(String status, Pageable pageable) {
        return apiKeyRepository.findByStatusAndIsDeletedFalse(status, pageable);
    }

    /**
     * 根据名称模糊查询API Key
     */
    @Override
    @Transactional(readOnly = true)
    public Page<ApiKey> findByNameContaining(String name, Pageable pageable) {
        return apiKeyRepository.findByNameContainingAndIsDeletedFalse(name, pageable);
    }

    /**
     * 更新API Key
     */
    @Override
    public ApiKey updateApiKey(Long id, String name, String permissions, String operatorId,
                               String description, Integer dailyLimit, Integer monthlyLimit, LocalDateTime expiresAt) {
        ApiKey apiKey = findById(id)
                .orElseThrow(() -> new IllegalArgumentException("API Key不存在: " + id));

        // 检查名称是否与其他API Key冲突
        if (!apiKey.getName().equals(name) && existsByName(name)) {
            throw new IllegalArgumentException("API Key名称已存在: " + name);
        }

        // 更新字段
        apiKey.setName(name);
        apiKey.setPermissions(permissions);
        apiKey.setDescription(description);
        apiKey.setDailyLimit(dailyLimit);
        apiKey.setMonthlyLimit(monthlyLimit);
        apiKey.setExpiresAt(expiresAt);
        apiKey.setUpdatedAt(LocalDateTime.now());

        // 保存更新
        ApiKey updatedApiKey = apiKeyRepository.save(apiKey);

        // 记录历史
        historyService.recordChange(updatedApiKey, "UPDATE", operatorId, "更新API Key信息");

        return updatedApiKey;
    }

    @Override
    public ApiKey updateApiKey(Long id, String name, String description, String permissions,
                               LocalDateTime expiryTime, Integer dailyLimit, Integer monthlyLimit,
                               String operatorId) {
        Optional<ApiKey> apiKeyOpt = findById(id);
        if (!apiKeyOpt.isPresent()) {
            throw new RuntimeException("API Key not found: " + id);
        }

        ApiKey apiKey = apiKeyOpt.get();

        // 记录历史
        historyService.recordUpdate(apiKey, operatorId);

        // 更新字段
        if (name != null) apiKey.setName(name);
        if (description != null) apiKey.setDescription(description);
        if (permissions != null) apiKey.setPermissions(permissions);
        if (expiryTime != null) apiKey.setExpiryTime(expiryTime);
        if (dailyLimit != null) apiKey.setDailyLimit(dailyLimit);
        if (monthlyLimit != null) apiKey.setMonthlyLimit(monthlyLimit);

        apiKey.setUpdatedAt(LocalDateTime.now());

        return apiKeyRepository.save(apiKey);
    }

    @Override
    public ApiKey updateApiKey(ApiKey apiKey) {
        try {
            // 验证API Key是否存在
            if (apiKey.getId() == null) {
                throw new IllegalArgumentException("API Key ID不能为空");
            }

            Optional<ApiKey> existingApiKey = findById(apiKey.getId());
            if (!existingApiKey.isPresent()) {
                throw new IllegalArgumentException("API Key不存在: " + apiKey.getId());
            }

            // 如果更新名称，检查名称是否已被其他API Key使用
            if (apiKey.getName() != null && !apiKey.getName().equals(existingApiKey.get().getName())) {
                if (existsByName(apiKey.getName())) {
                    throw new IllegalArgumentException("API Key名称已存在: " + apiKey.getName());
                }
            }

            // 记录历史
            historyService.recordChange(apiKey, "UPDATE", "system", "API Key updated");

            apiKey.setUpdatedAt(LocalDateTime.now());
            return apiKeyRepository.save(apiKey);
        } catch (Exception e) {
            throw new RuntimeException("更新API Key失败: " + e.getMessage(), e);
        }
    }

    @Override
    public ApiKey createApiKey(ApiKey apiKey) {
        try {
            // 验证必填字段
            if (apiKey.getName() == null || apiKey.getName().trim().isEmpty()) {
                throw new IllegalArgumentException("API Key名称不能为空");
            }

            // 检查名称是否已存在
            if (existsByName(apiKey.getName())) {
                throw new IllegalArgumentException("API Key名称已存在: " + apiKey.getName());
            }

            // 生成API Key值
            if (apiKey.getKeyValue() == null || apiKey.getKeyValue().isEmpty()) {
                String keyValue;
                do {
                    keyValue = generateApiKeyValue();
                } while (existsByKeyValue(keyValue));
                apiKey.setKeyValue(keyValue);
            }

            // 设置用户ID，如果为空则使用默认用户ID
            if (apiKey.getUserId() == null || apiKey.getUserId().trim().isEmpty()) {
                apiKey.setUserId(userService.getDefaultUserId());
            }

            // 设置默认值
            if (apiKey.getStatus() == null) {
                apiKey.setStatus("ACTIVE");
            }
            if (apiKey.getCreatedAt() == null) {
                apiKey.setCreatedAt(LocalDateTime.now());
            }
            apiKey.setUpdatedAt(LocalDateTime.now());
            apiKey.setIsDeleted(false);

            // 保存API Key
            ApiKey savedApiKey = apiKeyRepository.save(apiKey);

            // 记录历史
            historyService.recordChange(savedApiKey, "CREATE", "system", "API Key created");

            return savedApiKey;
        } catch (Exception e) {
            throw new RuntimeException("创建API Key失败: " + e.getMessage(), e);
        }
    }

    /**
     * 切换API Key状态
     */
    @Override
    public ApiKey toggleStatus(Long id, String operatorId) {
        ApiKey apiKey = findById(id)
                .orElseThrow(() -> new IllegalArgumentException("API Key不存在: " + id));

        String newStatus = "ACTIVE".equals(apiKey.getStatus()) ? "INACTIVE" : "ACTIVE";
        String operationType = "ACTIVE".equals(newStatus) ? "ACTIVATE" : "DEACTIVATE";
        String reason = "ACTIVE".equals(newStatus) ? "激活API Key" : "停用API Key";

        apiKey.setStatus(newStatus);
        apiKey.setUpdatedAt(LocalDateTime.now());

        ApiKey updatedApiKey = apiKeyRepository.save(apiKey);

        // 记录历史
        historyService.recordChange(updatedApiKey, operationType, operatorId, reason);

        return updatedApiKey;
    }

    /**
     * 激活API Key
     */
    @Override
    public ApiKey activate(Long id, String operatorId) {
        ApiKey apiKey = findById(id)
                .orElseThrow(() -> new IllegalArgumentException("API Key不存在: " + id));

        apiKey.setStatus("ACTIVE");
        apiKey.setUpdatedAt(LocalDateTime.now());

        ApiKey updatedApiKey = apiKeyRepository.save(apiKey);

        // 记录历史
        historyService.recordChange(updatedApiKey, "ACTIVATE", operatorId, "激活API Key");

        return updatedApiKey;
    }

    /**
     * 停用API Key
     */
    @Override
    public ApiKey deactivate(Long id, String operatorId) {
        ApiKey apiKey = findById(id)
                .orElseThrow(() -> new IllegalArgumentException("API Key不存在: " + id));

        apiKey.setStatus("INACTIVE");
        apiKey.setUpdatedAt(LocalDateTime.now());

        ApiKey updatedApiKey = apiKeyRepository.save(apiKey);

        // 记录历史
        historyService.recordChange(updatedApiKey, "DEACTIVATE", operatorId, "停用API Key");

        return updatedApiKey;
    }

    /**
     * 续期API Key
     */
    @Override
    public ApiKey renewApiKey(Long id, LocalDateTime newExpiryTime, String operatorId) {
        ApiKey apiKey = findById(id)
                .orElseThrow(() -> new IllegalArgumentException("API Key不存在: " + id));

        apiKey.setExpiresAt(newExpiryTime);
        apiKey.setUpdatedAt(LocalDateTime.now());

        ApiKey updatedApiKey = apiKeyRepository.save(apiKey);

        // 记录历史
        historyService.recordChange(updatedApiKey, "RENEW", operatorId, "续期API Key至: " + newExpiryTime);

        return updatedApiKey;
    }

    /**
     * 软删除API Key
     */
    @Override
    public boolean deleteApiKey(Long id, String operatorId) {
        ApiKey apiKey = findById(id)
                .orElseThrow(() -> new IllegalArgumentException("API Key不存在: " + id));

        apiKey.markAsDeleted();
        apiKeyRepository.save(apiKey);

        // 记录历史
        historyService.recordChange(apiKey, "DELETE", operatorId, "删除API Key");

        return true;
    }

    /**
     * 验证API Key是否有效
     *
     * @param keyValue API Key值
     * @return 是否有效
     */
    @Override
    @Transactional(readOnly = true)
    public boolean validateApiKey(String keyValue) {
        Optional<ApiKey> apiKey = findByKeyValue(keyValue);
        if (!apiKey.isPresent()) {
            return false;
        }

        ApiKey key = apiKey.get();

        // 检查状态
        if (!"ACTIVE".equals(key.getStatus())) {
            return false;
        }

        // 检查过期时间
        if (key.getExpiresAt() != null && key.getExpiresAt().isBefore(LocalDateTime.now())) {
            return false;
        }

        return true;
    }

    /**
     * 检查API Key是否具有指定权限
     *
     * @param keyValue   API Key值
     * @param permission 权限名称
     * @return 是否具有权限
     */
    @Override
    @Transactional(readOnly = true)
    public boolean hasPermission(String keyValue, String permission) {
        Optional<ApiKey> apiKey = findByKeyValue(keyValue);
        if (!apiKey.isPresent()) {
            return false;
        }

        ApiKey key = apiKey.get();

        // 检查API Key是否有效
        if (!validateApiKey(keyValue)) {
            return false;
        }

        // 检查权限
        String permissions = key.getPermissions();
        if (permissions == null || permissions.trim().isEmpty()) {
            return false;
        }

        // 支持通配符权限
        if ("*".equals(permissions.trim())) {
            return true;
        }

        // 检查具体权限
        String[] permissionArray = permissions.split(",");
        for (String perm : permissionArray) {
            if (perm.trim().equals(permission)) {
                return true;
            }
        }

        return false;
    }

    /**
     * 增加API Key使用次数
     *
     * @param keyValue API Key值
     * @return 是否成功
     */
    @Override
    public boolean incrementUsage(String keyValue) {
        Optional<ApiKey> apiKey = findByKeyValue(keyValue);
        if (!apiKey.isPresent()) {
            return false;
        }

        ApiKey key = apiKey.get();
        // 这里应该增加使用次数的逻辑
        // 由于当前实体类没有使用次数字段，这里只是示例
        return true;
    }

    /**
     * 重置API Key使用次数
     *
     * @param keyValue     API Key值
     * @param resetDaily   是否重置每日使用次数
     * @param resetMonthly 是否重置每月使用次数
     * @return 是否成功
     */
    @Override
    public boolean resetUsage(String keyValue, boolean resetDaily, boolean resetMonthly) {
        Optional<ApiKey> apiKey = findByKeyValue(keyValue);
        if (!apiKey.isPresent()) {
            return false;
        }

        ApiKey key = apiKey.get();
        // 这里应该重置使用次数的逻辑
        if (resetDaily) {
            // 重置每日使用次数
        }
        if (resetMonthly) {
            // 重置每月使用次数
        }

        return true;
    }

    /**
     * 生成新的API Key值
     */
    @Override
    public String generateApiKeyValue() {
        StringBuilder sb = new StringBuilder(API_KEY_LENGTH);
        for (int i = 0; i < API_KEY_LENGTH; i++) {
            sb.append(API_KEY_CHARS.charAt(RANDOM.nextInt(API_KEY_CHARS.length())));
        }
        return sb.toString();
    }

    /**
     * 检查API Key名称是否已存在
     */
    @Override
    @Transactional(readOnly = true)
    public boolean existsByName(String name) {
        return apiKeyRepository.existsByNameAndIsDeletedFalse(name);
    }

    /**
     * 检查API Key值是否已存在
     */
    @Override
    @Transactional(readOnly = true)
    public boolean existsByKeyValue(String keyValue) {
        return apiKeyRepository.existsByKeyValueAndIsDeletedFalse(keyValue);
    }

    /**
     * 获取API Key统计信息
     */
    @Override
    @Transactional(readOnly = true)
    public Map<String, Object> getStatistics() {
        Map<String, Object> stats = new HashMap<>();

        // 总数统计
        stats.put("total", getTotalCount());
        stats.put("active", getActiveCount());
        stats.put("disabled", getDisabledCount());
        stats.put("expired", getExpiredCount());

        // 状态分布
        stats.put("statusDistribution", getStatusDistribution());

        // 今日创建数量
        LocalDateTime startOfDay = LocalDate.now().atStartOfDay();
        long todayCreated = apiKeyRepository.countByCreatedAtGreaterThanEqualAndIsDeletedFalse(startOfDay);
        stats.put("todayCreated", todayCreated);

        // 即将过期的数量（7天内）
        LocalDateTime sevenDaysLater = LocalDateTime.now().plusDays(7);
        long expiringSoon = apiKeyRepository.countByExpiresAtBetweenAndIsDeletedFalse(LocalDateTime.now(), sevenDaysLater);
        stats.put("expiringSoon", expiringSoon);

        return stats;
    }

    /**
     * 获取用户的API Key统计
     */
    @Override
    @Transactional(readOnly = true)
    public Map<String, Object> getUserStatistics(String userId) {
        Map<String, Object> stats = new HashMap<>();
        stats.put("total", apiKeyRepository.countByUserIdAndIsDeletedFalse(userId));
        stats.put("active", apiKeyRepository.countByUserIdAndStatusAndIsDeletedFalse(userId, "ACTIVE"));
        stats.put("disabled", apiKeyRepository.countByUserIdAndStatusAndIsDeletedFalse(userId, "DISABLED"));
        return stats;
    }

    /**
     * 获取状态分布统计
     */
    @Override
    @Transactional(readOnly = true)
    public Map<String, Long> getStatusDistribution() {
        Map<String, Long> distribution = new HashMap<>();
        distribution.put("ACTIVE", apiKeyRepository.countByStatusAndIsDeletedFalse("ACTIVE"));
        distribution.put("DISABLED", apiKeyRepository.countByStatusAndIsDeletedFalse("DISABLED"));
        distribution.put("EXPIRED", getExpiredCount());
        return distribution;
    }

    /**
     * 获取每日创建统计
     */
    @Override
    @Transactional(readOnly = true)
    public List<Map<String, Object>> getDailyCreationStats(int days) {
        List<Map<String, Object>> stats = new ArrayList<>();

        for (int i = days - 1; i >= 0; i--) {
            LocalDate date = LocalDate.now().minusDays(i);
            LocalDateTime startOfDay = date.atStartOfDay();
            LocalDateTime endOfDay = date.atTime(23, 59, 59);

            long count = apiKeyRepository.countByCreatedAtBetweenAndIsDeletedFalse(startOfDay, endOfDay);

            Map<String, Object> dayStat = new HashMap<>();
            dayStat.put("date", date.toString());
            dayStat.put("count", count);
            stats.add(dayStat);
        }

        return stats;
    }

    /**
     * 查找即将过期的API Key
     */
    @Override
    @Transactional(readOnly = true)
    public List<ApiKey> findExpiringApiKeys(int days) {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime futureTime = now.plusDays(days);
        return apiKeyRepository.findByExpiresAtBetweenAndIsDeletedFalse(now, futureTime);
    }

    /**
     * 查找已过期的API Key
     */
    @Override
    @Transactional(readOnly = true)
    public List<ApiKey> findExpiredApiKeys() {
        LocalDateTime now = LocalDateTime.now();
        return apiKeyRepository.findByExpiresAtLessThanAndIsDeletedFalse(now);
    }

    /**
     * 查找超出限制的API Key
     */
    @Override
    @Transactional(readOnly = true)
    public List<ApiKey> findOverLimitApiKeys() {
        // 这里应该根据使用情况查找超出限制的API Key
        // 由于当前实体类没有使用次数字段，这里返回空列表
        return new ArrayList<>();
    }

    /**
     * 处理已过期的API Key
     */
    @Override
    public int handleExpiredApiKeys() {
        List<ApiKey> expiredKeys = findExpiredApiKeys();
        int count = 0;

        for (ApiKey apiKey : expiredKeys) {
            if (!"EXPIRED".equals(apiKey.getStatus())) {
                apiKey.setStatus("EXPIRED");
                apiKey.setUpdatedAt(LocalDateTime.now());
                apiKeyRepository.save(apiKey);

                // 记录历史
                historyService.recordHistory(apiKey, "EXPIRE", "system");
                count++;
            }
        }

        return count;
    }

    /**
     * 批量更新状态
     */
    @Override
    public int batchUpdateStatus(List<Long> ids, String status, String operatorId) {
        int count = 0;

        for (Long id : ids) {
            Optional<ApiKey> apiKeyOpt = findById(id);
            if (apiKeyOpt.isPresent()) {
                ApiKey apiKey = apiKeyOpt.get();
                String oldStatus = apiKey.getStatus();

                if (!oldStatus.equals(status)) {
                    apiKey.setStatus(status);
                    apiKey.setUpdatedAt(LocalDateTime.now());
                    apiKeyRepository.save(apiKey);

                    // 记录历史
                    historyService.recordHistory(apiKey, "BATCH_UPDATE_STATUS", operatorId);
                    count++;
                }
            }
        }

        return count;
    }

    /**
     * 批量删除API Key
     */
    @Override
    public int batchDelete(List<Long> ids, String operatorId) {
        int count = 0;

        for (Long id : ids) {
            if (deleteApiKey(id, operatorId)) {
                count++;
            }
        }

        return count;
    }

    /**
     * 导出API Key数据
     */
    @Override
    @Transactional(readOnly = true)
    public String exportApiKeys(String userId, String status) {
        List<ApiKey> apiKeys;

        if (userId != null && status != null) {
            apiKeys = apiKeyRepository.findByUserIdAndStatusAndIsDeletedFalse(userId, status);
        } else if (userId != null) {
            Page<ApiKey> page = apiKeyRepository.findByUserIdAndIsDeletedFalse(userId, Pageable.unpaged());
            apiKeys = page.getContent();
        } else if (status != null) {
            Page<ApiKey> page = apiKeyRepository.findByStatusAndIsDeletedFalse(status, Pageable.unpaged());
            apiKeys = page.getContent();
        } else {
            Page<ApiKey> page = apiKeyRepository.findByIsDeletedFalse(Pageable.unpaged());
            apiKeys = page.getContent();
        }

        StringBuilder csv = new StringBuilder();
        csv.append("ID,名称,API Key,权限,状态,用户ID,每日限制,每月限制,过期时间,创建时间,更新时间\n");

        for (ApiKey apiKey : apiKeys) {
            csv.append(apiKey.getId()).append(",")
                    .append(escapeCSV(apiKey.getName())).append(",")
                    .append(escapeCSV(apiKey.getKeyValue())).append(",")
                    .append(escapeCSV(apiKey.getPermissions())).append(",")
                    .append(escapeCSV(apiKey.getStatus())).append(",")
                    .append(escapeCSV(apiKey.getUserId())).append(",")
                    .append(apiKey.getDailyLimit() != null ? apiKey.getDailyLimit() : "").append(",")
                    .append(apiKey.getMonthlyLimit() != null ? apiKey.getMonthlyLimit() : "").append(",")
                    .append(apiKey.getExpiresAt() != null ? apiKey.getExpiresAt().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME) : "").append(",")
                    .append(apiKey.getCreatedAt() != null ? apiKey.getCreatedAt().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME) : "").append(",")
                    .append(apiKey.getUpdatedAt() != null ? apiKey.getUpdatedAt().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME) : "").append("\n");
        }

        return csv.toString();
    }

    /**
     * 清理已删除的API Key
     */
    @Override
    public int cleanupDeletedApiKeys(int retentionDays) {
        LocalDateTime cutoffTime = LocalDateTime.now().minusDays(retentionDays);
        List<ApiKey> deletedKeys = apiKeyRepository.findByIsDeletedTrueAndUpdatedAtLessThan(cutoffTime);

        if (!deletedKeys.isEmpty()) {
            apiKeyRepository.deleteAll(deletedKeys);
            return deletedKeys.size();
        }

        return 0;
    }

    /**
     * 保存API Key
     */
    public ApiKey save(ApiKey apiKey) {
        if (apiKey.getId() == null) {
            // 新建
            apiKey.setCreatedAt(LocalDateTime.now());
            apiKey.setUpdatedAt(LocalDateTime.now());
            apiKey.setIsDeleted(false);
        } else {
            // 更新
            apiKey.setUpdatedAt(LocalDateTime.now());
        }
        return apiKeyRepository.save(apiKey);
    }

    /**
     * 获取禁用状态的API Key数量
     */
    @Override
    @Transactional(readOnly = true)
    public long getDisabledCount() {
        return apiKeyRepository.countByStatusAndIsDeletedFalse("DISABLED");
    }

    /**
     * 获取已过期的API Key数量
     */
    @Override
    @Transactional(readOnly = true)
    public long getExpiredCount() {
        LocalDateTime now = LocalDateTime.now();
        return apiKeyRepository.countByExpiresAtLessThanAndIsDeletedFalse(now);
    }

    /**
     * 获取活跃状态的API Key数量
     */
    @Override
    @Transactional(readOnly = true)
    public long getActiveCount() {
        return apiKeyRepository.countByStatusAndIsDeletedFalse("ACTIVE");
    }

    /**
     * 获取API Key总数量
     */
    @Override
    public long getTotalCount() {
        return apiKeyRepository.countByIsDeletedFalse();
    }

    /**
     * 删除API Key（简化版本）
     */
    @Override
    public void deleteApiKey(Long id) {
        deleteApiKey(id, "system");
    }

    /**
     * 续期API Key（简化版本）
     */
    @Override
    public ApiKey renewApiKey(Long id, int days) {
        LocalDateTime newExpiryTime = LocalDateTime.now().plusDays(days);
        return renewApiKey(id, newExpiryTime, "system");
    }

    /**
     * 切换API Key状态（简化版本）
     */
    @Override
    public ApiKey toggleStatus(Long id) {
        return toggleStatus(id, "system");
    }

    /**
     * 分页查询API Keys
     */
    /**
     * 多条件分页查询API Key
     */
    @Override
    public Page<ApiKey> findApiKeys(String userId, String status, String permission, Pageable pageable) {
        // 使用Specification进行动态查询
        Specification<ApiKey> spec = (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();

            // 基础条件：未删除
            predicates.add(criteriaBuilder.equal(root.get("isDeleted"), false));

            // 用户ID过滤
            if (userId != null && !userId.trim().isEmpty()) {
                predicates.add(criteriaBuilder.equal(root.get("userId"), userId));
            }

            // 状态过滤
            if (status != null && !status.trim().isEmpty()) {
                predicates.add(criteriaBuilder.equal(root.get("status"), status));
            }

            // 权限过滤
            if (permission != null && !permission.trim().isEmpty()) {
                predicates.add(criteriaBuilder.like(root.get("permissions"), "%" + permission + "%"));
            }

            return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
        };

        return apiKeyRepository.findAll(spec, pageable);
    }

    /**
     * 转义CSV字段值
     *
     * @param value 原始值
     * @return 转义后的值
     */
    private String escapeCSV(String value) {
        if (value == null) {
            return "";
        }

        // 如果包含逗号、引号或换行符，需要用引号包围并转义内部引号
        if (value.contains(",") || value.contains("\"") || value.contains("\n")) {
            return "\"" + value.replace("\"", "\"\"") + "\"";
        }

        return value;
    }
}